package com.kucai.yifaqapp.model.network;

import android.content.Context;
import android.support.annotation.NonNull;

import com.google.gson.Gson;
import com.kucai.yifaqapp.global.App;
import com.kucai.yifaqapp.global.HttpAdress;
import com.kucai.yifaqapp.util.EventBus.ReloginEvent;
import com.kucai.yifaqapp.util.SYSOUtils;

import org.greenrobot.eventbus.EventBus;

import java.io.IOException;
import java.net.URLDecoder;
import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.Collections;
import java.util.concurrent.TimeUnit;

import okhttp3.Cache;
import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Protocol;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okhttp3.logging.HttpLoggingInterceptor;
import okio.Buffer;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * 网络请求json工具类
 */
public class HttpJsonUtils {
    private static final long CONNECT_TIMEOUT = 15;
    private static final long WRITE_TIMEOUT = 15;
    private static final long READ_TIMEOUT = 15;
    public static boolean TEST = true;//测试标记
    private static HttpJsonUtils instance;
    private static Retrofit mRetrofit;
    private static HttpJsonApi httpApi;
    private static Context mContext = App.getContext();
    private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    private HttpJsonUtils(Context context) {
        this.mContext = context;
        initRetrofit(_getOkHttpClient());
    }

    /**
     * 初始化Retrofit
     *
     * @param client
     */
    private void initRetrofit(OkHttpClient client) {
        mRetrofit = new Retrofit.Builder()
                .client(client)
                .baseUrl("https://www.9780app.com")
                .addConverterFactory(GsonConverterFactory.create(new Gson()))
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build();
    }

    /**
     * 初始化OkHttpClient
     *
     * @return
     */
    @NonNull
    private OkHttpClient _getOkHttpClient() {
        OkHttpClient.Builder clientBuilder = new OkHttpClient.Builder()
                .protocols(Collections.singletonList(Protocol.HTTP_1_1))
                .retryOnConnectionFailure(true)//周一新增
                .addInterceptor(new HttpInterceptor())
                .connectTimeout(CONNECT_TIMEOUT, TimeUnit.SECONDS)
                .writeTimeout(WRITE_TIMEOUT, TimeUnit.SECONDS)
                .readTimeout(READ_TIMEOUT, TimeUnit.SECONDS)
                .cache(new Cache(App.cacheDir, 1024 * 1024 * 100));
        if (TEST) {
            //网络日志
            HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
                @Override
                public void log(String message) {
                    try {
                        String finalmsg = message.replaceAll("%(?![0-9a-fA-F]{2})", "%25");
                        String text = URLDecoder.decode(finalmsg, "utf-8");
                        if (text.contains("{\"status\":false,\"msg\":\"\",\"code\":600}")) {
                            EventBus.getDefault().post(new ReloginEvent("600"));
                        }
                        SYSOUtils.tagLog("HttpLog_Json", text);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
            httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
            clientBuilder.addInterceptor(httpLoggingInterceptor);
        }
        return clientBuilder.build();
    }


    public static HttpJsonUtils getInstance() {
        if (instance == null) {
            synchronized (HttpJsonUtils.class) {
                if (instance == null) {
                    instance = new HttpJsonUtils(mContext);
                }
            }
        }
        return instance;
    }

    /**
     * @return mRetrofit
     */
    public static HttpJsonApi getHttpApiInstance() {
        if (instance == null) {
            synchronized (HttpJsonUtils.class) {
                if (instance == null) {
                    instance = new HttpJsonUtils(mContext);
                    httpApi = mRetrofit.create(HttpJsonApi.class);
                }
            }
        }
        return httpApi;
    }

    /**
     * Interceptor
     * 加密请求内容
     */
    private class HttpInterceptor implements Interceptor {
        private final Charset UTF8 = Charset.forName("UTF-8");

        @Override
        public Response intercept(Chain chain) throws IOException {
            Request oldRequest = chain.request();
            // 添加新的参数
            HttpUrl.Builder authorizedUrlBuilder = oldRequest.url().newBuilder().scheme(oldRequest.url().scheme())
                    .host(oldRequest.url().host())
                    .addQueryParameter("source", "android");//在这个请求里面添加一个请求参数
            // 新的请求
            Request newRequest = oldRequest.newBuilder()
                    .method(oldRequest.method(), oldRequest.body())
                    .url(authorizedUrlBuilder.build())
                    .addHeader("Content-Type", "application/json; charset=utf-8")
                    .build();//再定义一个新的Request请求，再把添加了请求参数的请求放到新的请求里面来请求数据
            RequestBody requestBody = newRequest.body();
            String body = null;
            if (requestBody != null) {
                Buffer buffer = new Buffer();
                requestBody.writeTo(buffer);
                Charset charset = UTF8;
                MediaType contentType = requestBody.contentType();
                if (contentType != null) {
                    charset = contentType.charset(UTF8);
                }
                body = buffer.readString(charset);
            }
            long startNs = System.nanoTime();
            Response response = chain.proceed(newRequest);
            long tookMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNs);
            ResponseBody responseBody = response.body();
            String rBody = null;
            return response;
        }
    }


}
